package com.nemodynamic.cattivial;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.facebook.Session;
import com.nemodynamic.cattivial.facebook.AsyncTaskGetMyImage;
import com.nemodynamic.cattivial.facebook.FacebookUtils;
import com.nemodynamic.cattivial.gamecenter.ChallengeUtils;
import com.nemodynamic.cattivial.gamecenter.NotificationReceiver;
import com.nemodynamic.cattivial.gamecenter.beans.Challenge;
import com.nemodynamic.cattivial.utils.ConnectionUtils;
import com.nemodynamic.cattivial.utils.DLog;
import com.nemodynamic.cattivial.utils.ImageUtils;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

public class Cattivial extends SherlockFragmentActivity {
	private static final String TAG = "Cattivial";
	private boolean isStarted = false;
	private int level = 5;
	private View startBox;
	private ImageView startButton;
	private Animation pulseAnimation;
	private ViewGroup gameContainer;
	private TextView score;
	private TextView question;
	private TextView[] resultsTextViews;
	private CattivialGameTask startGameTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getSupportActionBar().hide();
		// Layout
		pulseAnimation = AnimationUtils.loadAnimation(this, R.anim.startbutton_pulse);
		startBox = findViewById(R.id.startBox);
		startButton = (ImageView) findViewById(R.id.startButton);
		startButton.setImageBitmap(ImageUtils.getStartButtonImages(((BitmapDrawable) getResources().getDrawable(R.drawable.user_placeholder)).getBitmap()));
		startButton.setOnTouchListener(onStartButtonTouch);
		gameContainer = (ViewGroup) findViewById(R.id.game_container);
		score = (TextView) findViewById(R.id.score);
		question = (TextView) findViewById(R.id.question); 
		resultsTextViews = new TextView[3];
		resultsTextViews[0] = (TextView) findViewById(R.id.result1);
		resultsTextViews[1] = (TextView) findViewById(R.id.result2);
		resultsTextViews[2] = (TextView) findViewById(R.id.result3);
		startGameTask = new CattivialGameTask(this, startBox, startButton, score, question, resultsTextViews, gameContainer, level);
		// Debug key
		printDebugHash(); //For develop purpose
		initializeParse();
		initializePush();
		initializeTrack();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onResume() {
		Session session = null;
		if ((session = FacebookUtils.isSession(this)) != null) {
			(new AsyncTaskGetMyImage(this,session, startButton)).execute();
		}
		super.onResume();

	}

	public void start(View v) {
		if (startGameTask.getStatus() == AsyncTask.Status.FINISHED) {
			//level++;
			startGameTask = new CattivialGameTask(this, startBox, startButton, score, question, resultsTextViews, gameContainer, level);
			startGameTask.execute(level);
		} else if (startGameTask.getStatus() != AsyncTask.Status.RUNNING) {
			startGameTask.execute(level);
		}

	}

	OnTouchListener onStartButtonTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (startGameTask.getStatus() != AsyncTask.Status.RUNNING) {
				Rect startButtonRect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					startButton.startAnimation(pulseAnimation);
				} else if (event.getAction() == MotionEvent.ACTION_UP && startButtonRect.contains((int) event.getX(), (int) event.getY())) {
					pulseAnimation.cancel();
					if(ConnectionUtils.isOnline(Cattivial.this)){
						start(v);
					}else{
						startButton.setImageBitmap(ImageUtils.getStartButtonImages(((BitmapDrawable)getResources().getDrawable(R.drawable.antenna)).getBitmap()));
					}
					
				} else if (event.getAction() == MotionEvent.ACTION_MOVE && !startButtonRect.contains((int) event.getX(), (int) event.getY())) {
					pulseAnimation.cancel();
				}
			}
			return true;
		}
	};
	
	private void printDebugHash(){
		PackageInfo info;
		try {
			info = getPackageManager().getPackageInfo("com.nemodynamic.cattivial", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md;
				md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				String something = new String(Base64.encode(md.digest(), 0));
				DLog.e(TAG, "Hash" + something);
			}
		} catch (NameNotFoundException e1) {
			DLog.e("name not found", e1.toString());
		} catch (NoSuchAlgorithmException e) {
			DLog.e("no such an algorithm", e.toString());
		} catch (Exception e) {
			DLog.e("exception", e.toString());
		}
	}

	public void onBackPressed() {
		ChallengeUtils.initGameForChallenges("PietroID", "PietroLeggero");
		Challenge challenge = ChallengeUtils.findCasualOpenChallenge("Test Challenge");
		if(challenge!=null){
			ChallengeUtils.proposeChallenge(challenge, "Voglio iniziare una sfida con te!");
		}else{
			DLog.e("info", "Challenge non trovata");
		}
		GameManager gm = GameManager.getCurrentInstance();
		if (gm != null && gm.isGameStarted()) {
			startBox.setVisibility(View.VISIBLE);
			resultsTextViews[0].setVisibility(View.INVISIBLE);
			resultsTextViews[1].setVisibility(View.INVISIBLE);
			resultsTextViews[2].setVisibility(View.INVISIBLE);
			score.setVisibility(View.INVISIBLE);
			question.setVisibility(View.INVISIBLE);
			gm.stopGame();
			isStarted = false;
		}

	};
	
	private void initializeParse(){
	    Parse.initialize(this, "KxJJCJg24Qd3wlybHybLHdzPQCbRgn29mWfmou53", "TdQwZEwLjaxvPMw1EI8i112LoYPPyGzEWuYogV4m"); 
	   
	}
	private void initializePush(){
		PushService.setDefaultPushCallback(this, Cattivial.class);
		ParseInstallation.getCurrentInstallation().saveInBackground();
	}
	private void initializeTrack(){
		 ParseAnalytics.trackAppOpened(getIntent());	
	}
	
}
